package mvc.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvc.action.BaseAction;
import mvc.form.BaseForm;
import mvc.form.XmlBean;
import mvc.unti.FullBean;

public class ActionServlet extends HttpServlet {

	private static final long serialVersionUID = 2411155147670549404L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = this.getPath(request.getServletPath());
		Map<String, XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("s");
		XmlBean xmlBean = map.get(path);
		String beanClass = xmlBean.getBeanClass();
		BaseForm baseForm = FullBean.full(beanClass, request);
		String actionClass = xmlBean.getActionClass();
		BaseAction baseAction = null;
		String url = "";
		try {
			Class clazz = Class.forName(actionClass);
			baseAction = (BaseAction) clazz.newInstance();
			url = baseAction.execute(request, baseForm, xmlBean.getActionForward());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

	private String getPath(String servletPath) {
		return servletPath.split("\\.")[0];
	}
}
